# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : Pan
# @E-mail :
# @Date   : 2025-05-19 10:51:33
# @Brief  :
# --------------------------------------------------------
"""
import os
import json
import time
import logging
import traceback
import asyncio
from fastapi import APIRouter, Header
from pydantic import BaseModel
from typing import Optional, Dict, List, Any
from app.api.status import Status, response
from app.utils.log import logger
from pybaseutils import time_utils
from app.core.pipeline import Pipeline

pipe = Pipeline()

router = APIRouter(
    prefix="/v1",
    tags=["interface"],
)


class Inputs(BaseModel):
    model: Optional[str] = ""
    messages: Optional[List] = []
    stream: Optional[bool] = False
    max_new_tokens: Optional[int] = None
    top_p: Optional[float] = None
    temperature: Optional[float] = None
    repetition_penalty: Optional[float] = None
    reqid: Optional[str] = ""


@router.post("/chat/completions")
async def chat(inputs: Inputs):
    t0 = time.time()
    reqid = inputs.reqid
    logger.info('start  reqid={:20s} interface be called'.format(reqid))
    # TODO {"level": 0, "role": "assistant", "content": msg, "code": 5000, "msg": msg}
    result = pipe.task(inputs.model_dump())  # model_dump()将inputs转换为字典
    result = {"choices": [{"message": result}], "model": inputs.model, "id": reqid}
    t1 = time.time()
    elapsed = (t1 - t0) * 1000
    logger.info("finish reqid={:20s} elapsed: {:4.3f}ms".format(reqid, elapsed))
    return result


@router.post("/chat/simple")
async def chat(inputs: Inputs):
    t0 = time.time()
    reqid = inputs.reqid
    inputs = inputs.model_dump()  # 将inputs转换为字典
    logger.info('start  reqid={:20s} interface be called'.format(reqid))
    data = pipe.task(inputs)
    t1 = time.time()
    elapsed = (t1 - t0) * 1000
    logger.info("finish reqid={:20s} elapsed: {:4.3f}ms".format(reqid, elapsed))
    return response(data=data, reqid=reqid)


if __name__ == "__main__":
    from datetime import datetime
    from pybaseutils import config_utils

    inputs = {"model": "123456789", "messages": [], "reqid": "123456789"}
    inputs = config_utils.Dict2Obj(inputs)
    result = asyncio.run(chat(inputs))
    print(result)
